import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import Login from './views/Login.vue'
import Home from './views/Home.vue'
import FinanceVouchers from './views/FinanceVouchers.vue'
import ProductionOrders from './views/ProductionOrders.vue'
import SupplyChain from './views/SupplyChain.vue'
import HR from './views/HR.vue'

// 创建路由
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/finance/vouchers',
    name: 'FinanceVouchers',
    component: FinanceVouchers
  },
  {
    path: '/production/orders',
    name: 'ProductionOrders',
    component: ProductionOrders
  },
  {
    path: '/supply',
    name: 'SupplyChain',
    component: SupplyChain
  },
  {
    path: '/hr',
    name: 'HR',
    component: HR
  },
  // 重定向根路径到首页
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
]

// 创建路由器实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 添加路由守卫
router.beforeEach((to, from, next) => {
  // 获取用户存储实例
  const userStore = useUserStore()
  
  // 检查是否需要认证
  const requiresAuth = !['/login'].includes(to.path)
  const token = userStore.token || localStorage.getItem('token')
  
  if (requiresAuth && !token) {
    // 需要认证但没有token，重定向到登录页
    next('/login')
  } else if (token && to.path === '/login') {
    // 已登录且访问登录页，重定向到首页
    next('/')
  } else {
    // 其他情况允许访问
    next()
  }
})

export default router